<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="node_modules/xterm/css/xterm.css" />
    <script src="node_modules/xterm/lib/xterm.js"></script>
    <script src="./term.js"></script>
    <title>Document</title>
</head>

<body>
    <div id="terminal" style="height: 95vh;"></div>
    <script>
        var term = new Terminal({
            theme: Solarized_Darcula,
            fontSize: 13,
            convertEol: true,
            disableStdin: false
        });
        term.open(document.getElementById('terminal'));

        // 调整窗口
        const fitSize = () => {
            var geometry = getTermSize(term)
            term.resize(geometry.cols, geometry.rows)
        }
        // 终端大小调整
        fitSize()
        // 监控浏览器窗口resize
        window.onresize = fitSize

        // websocket链接
        const connect = () => {
            // 建立websocket链接
            let socket = new WebSocket(`ws://127.0.0.1:8080/cmdb/api/v1/secrets/cjg2madmjd0h667tdhg0/sync_resource`);
            socket.onopen = function (e) {
                console.log('socket open')
                console.log(e)
            };
            socket.onmessage = function (event) {
                // server 发送给terminal的数据
                console.log(event)
                term.write(event.data)
            };
            socket.onclose = function (event) {
                if (event.wasClean) {
                    term.write(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
                } else {
                    // e.g. server process killed or network down
                    // event.code is usually 1006 in this case
                    term.write('[close] Connection died');
                }
            };
            socket.onerror = function (error) {
                term.write(`[error]`);
            };
        }

        // 调用connect进行链接(  为了方便重连)
        connect()

    </script>
</body>

</html>